<template>
    <label class="c-checkbox" :class="{'c-checkbox-checked': inputVal}">
        <span class="c-checkbox-bg">
            <input type="checkbox" v-model="inputVal" @change="handleChange">
        </span>
        <span><slot></slot></span>
    </label>
</template>

<script>
    export default {
        name: "CCheckbox",
        props: {
            value: {
                type: [String, Number, Boolean],
                default: false
            },
            // 选中时的值，默认为true
            trueValue: {
                type: [String, Number, Boolean],
                default: true
            },
            // 没有选中时的值
            falseValue: {
                type: [String, Number, Boolean],
                default: false
            },
        },
        data() {
            return {
                inputVal: this.value === this.trueValue,
            };
        },
        watch: {
            value(newVal) {
                this.inputVal = newVal === this.trueValue;
            }
        },
        methods: {
            handleChange() {
                const val = this.inputVal ? this.trueValue : this.falseValue;
                this.$emit('input', val);
                this.$emit('on-change', val);
            }
        }
    };
</script>

<style lang="less">
    .c-checkbox {
        cursor: pointer;

        .c-checkbox-bg {
            display: inline-block;
            width: 14px;
            height: 14px;
            border-radius: 2px;
            vertical-align: middle;
            position: relative;
            overflow: hidden;
            border: 1px solid #ddd;

            >input, &:before, &:after {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 1;
            }

            >input {
                background: #fff;
                border: none;
            }

            &:before {
                z-index: 10;
                display: block;
                content: '';
                background: #fff;
                box-shadow: 0px 0px 4px #eceaea inset;
            }
            &:after {
                z-index: 100;
                display: block;
                content: '';
                width: 8px;
                height: 3px;
                top: 3px;
                left: 2px;
                border: 2px solid transparent;
                border-top: 0;
                border-right: 0;
                transform: rotate(-45deg);
            }
        }

        &-checked {
            .c-checkbox-bg {
                &:before {
                    background: @color-base;
                    box-shadow: none;
                }
                &:after {
                    border-color: #fff;
                }
            }
        }
        &:hover {
            .c-checkbox-bg {
                border: 1px solid #bbb;
            }
        }
    }
</style>
